<?php

// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: rainfer <81818832@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\User as UserModel;
use app\admin\model\AuthRule;
use app\admin\model\Organize as OrgModel;
use think\Db;
use think\Cache;
use think\Session;


class Admin extends Base
{
    /**
     * 用户列表
     */
    public function admin_list() 
    {
        $search_name = trim(input('search_name'));
        $company_type = input('company_type');
        $isvalid = input('isvalid');
        $position = trim(input('position'));

        $where_cond = array();
        //公司类型
        if(isset($company_type)){
            if(!empty($company_type)){
                $where_cond['organize.org_type'] = $company_type;
            }
        }else{
            $company_type = 1;
            $where_cond['organize.org_type'] = $company_type;
        }

        //状态
        if (isset($isvalid) && $isvalid!='') {
            $where_cond['user.isvalid'] = intval($isvalid);
        }
        //职务
        if (isset($position) && !empty($position)) {
            $where_cond['position.id'] = $position;
        }
        if (isset($search_name) && !empty($search_name)) {
            $where_cond['user.name'] = array('like', "%" . $search_name . "%");
        }
//        if (isset($search_name) && !empty($search_name)) {
//            $where_cond['user.name'] = array('like', "%" . $search_name . "%");
//        }
//        if (isset($search_name) && !empty($search_name)) {
//            $where_cond['user.name'] = array('like', "%" . $search_name . "%");
//        }
        $user_list = Db::name('user')
            ->join('dept', 'dept.id = user.dept_id', 'left')
            ->join('organize', 'organize.id = user.org_id', 'left')
            ->join('position', 'user.position = position.id', 'left')
            ->where($where_cond)
            ->order('user.id','desc')
            ->field('user.id,user.user_name,user.name,user.admin_hits,user.isvalid,user.phone,user.last_login_time,dept.name as dept_name,position.name as position_name,organize.name as company_name')
            ->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
        $page = $user_list->render();

        //部门数据
        $dept_list = Db::name('dept')->where(array('isvalid' => 1))->select();
        //职务数据
        $position_list = Db::name('position')->where(array('isvalid' => 1))->select();
        //公司类别
        $orgModel = new OrgModel;
        $org_type = $orgModel->getOrgType();

        $this->assign('search_name', $search_name);
        $this->assign('company_type', $company_type);
        $this->assign('isvalid', $isvalid);
        $this->assign('position', $position);
        $this->assign('admin_list', $user_list);
        $this->assign('page', $page);
        $this->assign('dept_list', $dept_list);
        $this->assign('position_list', $position_list);
        $this->assign('org_type', $org_type);
        $this->assign('login_token',config('login_token'));
        $this->assign('url_time',time());
        return $this->fetch();
    }

    /**
     * 用户添加
     */
    public function admin_add() 
    {
        $auth_group = Db::name('auth_group')->select();
        $this->assign('auth_group', $auth_group);
        $orgModel = new OrgModel;
        //公司类别
        $org_type = $orgModel->getOrgType();
        //职务
        $position_list = Db::name('position')->where(array('isvalid' => 1))->select();

        $this->assign('org_type', $org_type);
        $this->assign('position_list', $position_list);
        return $this->fetch();
    }

    /**
     * 用户添加操作
     */
    public function admin_runadd()
    {
        $request=request();
        $add_data = array();
        if($request->param("dept_id")){
            $add_data['dept_id'] = intval(input('dept_id'));
        }
        
        $add_data['org_id'] = intval(input('org_id'));
        $add_data['name'] = trim(input('name'));
        $add_data['phone'] = trim(input('phone'));
        $add_data['sex'] = intval(input('sex'));
        $add_data['user_name'] = trim(input('user_name'));
        $add_data['password'] = md5(trim(input('password')));
        $add_data['user_type'] = intval(input('user_type'));

        if($request->param("position")){
            $add_data['position'] = intval(input('position'));
        }
        $add_data['isvalid'] = 1;
        $add_data['create_time'] = time();
        $add_data['last_login_ip'] = request()->ip();
        //数据校验
        $result=$this->validate($add_data,'Admin');

        if(true!==$result){
            //如果通不过,显示错误信息,并阻止页面提交
            $this->error($result);
        }
        $group_id_arr = array();
        $group_id = trim(input('group_id'));
        if (is_string($group_id) && !empty($group_id)) {
            $group_id_arr = explode(',', $group_id);
        }

        //用户名是否存在
        $user_model = new UserModel;
        $check_result = $user_model->checkouUserName($add_data['user_name']);
        if($check_result){
            $add_result = $user_model->add($add_data, $group_id_arr);
            if ($add_result) {
                $this->success('用户添加成功', url('admin/Admin/admin_list'));
            } else {
                $this->error('用户添加失败', url('admin/Admin/admin_list'));
            }
        }else{
            $this->error('该用户名已存在');
        }
    }

    /**
     * 用户修改
     */
    public function admin_edit() 
    {
        $auth_group = Db::name('auth_group')->select();
        $admin_list = Db::name('user')->find(input('id'));
        $auth_group_access_list = Db::name('auth_group_access')->where(array('uid' => $admin_list['id']))->select();
        $auth_group_access = array();
        if (is_array($auth_group_access_list) && !empty($auth_group_access_list)) {
            foreach ($auth_group_access_list as $key => $value) {
                $auth_group_access[] = $value['group_id'];
            }
        }
        $orgModel = new OrgModel;
        //公司类别
        $org_type = $orgModel->getOrgType();
        //当前公司类别下的组织机构
        $where_cond = array(
            'org_type' => intval($admin_list['user_type']),
            'isvalid' => 1
        );
        $org_list = Db::name('organize')->where($where_cond)->field('id,name')->select();
        //当前组织机构下的部门
        $where_cond = array(
            'org_id' => intval($admin_list['org_id']),
            'isvalid' => 1
        );
        $dept_list = db('dept')->where($where_cond)->field('id,name,pid')->select();
        $dept_tree_arr = returnTree($dept_list , array() , 0);
        //职务
        $position_list = Db::name('position')->where(array('isvalid' => 1))->select();

        $this->assign('org_list', $org_list);
        $this->assign('dept_list', $dept_tree_arr);
        $this->assign('org_type', $org_type);
        $this->assign('position_list', $position_list);
        $this->assign('admin_list', $admin_list);
        $this->assign('auth_group', $auth_group);
        $this->assign('auth_group_access', $auth_group_access);
        return $this->fetch();
    }

    /**
     * 用户修改操作
     */
    public function admin_runedit() 
    {
        $id = intval(input('id'));
        $auth_group_str = trim(input('group_id'));

        $update_data = array();
        $update_data['id'] = $id;
        $update_data['user_name'] = trim(input('user_name'));
        $update_data['dept_id'] = intval(input('dept_id'));
        $update_data['org_id'] = intval(input('org_id'));
        $update_data['name'] = trim(input('name'));
        $update_data['phone'] = trim(input('phone'));
        $update_data['password'] = trim(input('password'));
        $update_data['sex'] = intval(input('sex'));
        $update_data['user_type'] = intval(input('user_type'));
        $update_data['position'] = intval(input('position'));
        if($update_data['user_type'] == 2){
            $update_data['position'] = '';
        }
        $update_data['update_time'] = time();
        //数据校验
        $result=$this->validate($update_data,'Admin');
        
        if(true!==$result){
            //如果通不过,显示错误信息,并阻止页面提交
            $this->error($result);
        }

        if (isset($id) && !empty($id)) {
            $user_model = new UserModel;
            $rst = $user_model->edit($id, $update_data, $auth_group_str);
        }
        if (isset($rst) && $rst !== false) {
            $this->success('账号信息修改成功', url('admin/Admin/admin_list'));
        } else {
            $this->error('账号信息修改失败', url('admin/Admin/admin_list'));
        }
    }

    

    /**
     * 管理员开启/禁止
     */
    public function admin_state() 
    {
        $id = input('x');
        if (empty($id)) {
            $this->error('用户ID不存在', url('admin/Admin/admin_list'));
        }
        $status = Db::name('user')->where('id', $id)->value('isvalid'); //判断当前状态情况
        if ($status == 1) {
            $statedata = array('isvalid' => 0);
            Db::name('user')->where('id', $id)->setField($statedata);
            //微信状态同步
            $data = array(
                'id' => $id,
                'isvalid' => 0
            );
            $user_model = new UserModel;
            $this->success('状态禁止');
        } else {
            $statedata = array('isvalid' => 1);
            Db::name('user')->where('id', $id)->setField($statedata);
            //微信状态同步
            $data = array(
                'id' => $id,
                'isvalid' => 1
            );
            $user_model = new UserModel;
            $this->success('状态开启');
        }
    }

    /**
     * 用户组列表
     */
    public function admin_group_list() 
    {
        $auth_group = Db::name('auth_group')->select();
        $this->assign('auth_group', $auth_group);
        return $this->fetch();
    }

    /**
     * 用户组添加
     */
    public function admin_group_add() 
    {
        return $this->fetch();
    }

    /**
     * 用户组添加操作
     */
    public function admin_group_runadd() 
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/Admin/admin_group_list'));
        } else {
            $sldata = array(
                'title' => input('title'),
                'status' => input('status', 0),
                'rules' => '',
                'addtime' => time(),
            );
            //数据校验
            $result=$this->validate($sldata,'AdminGroup');
            if(true!==$result){
                //如果通不过,显示错误信息,并阻止页面提交
                $this->error($result);
            }
            $rst = Db::name('auth_group')->insert($sldata);
            if ($rst !== false) {
                $this->success('用户组添加成功', url('admin/Admin/admin_group_list'));
            } else {
                $this->error('用户组添加失败', url('admin/Admin/admin_group_list'));
            }
        }
    }

    /**
     * 用户组删除操作
     */
    public function admin_group_del() 
    {
        $rst = Db::name('auth_group')->delete(input('id'));
        if ($rst !== false) {
            $this->success('用户组删除成功', url('admin/Admin/admin_group_list'));
        } else {
            $this->error('用户组删除失败', url('admin/Admin/admin_group_list'));
        }
    }

    /**
     * 用户组编辑
     */
    public function admin_group_edit() 
    {
        $group = Db::name('auth_group')->find(input('id'));
        $this->assign('group', $group);
        return $this->fetch();
    }

    /**
     * 用户组编辑操作
     */
    public function admin_group_runedit() 
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/Admin/admin_group_list'));
        } else {
            $sldata = array(
                'id' => input('id'),
                'title' => input('title'),
                'status' => input('status'),
            );
            //数据校验
            $result=$this->validate($sldata,'AdminGroup');
            if(true!==$result){
                //如果通不过,显示错误信息,并阻止页面提交
                $this->error($result);
            }
            Db::name('auth_group')->update($sldata);
            $this->success('用户组修改成功', url('admin/Admin/admin_group_list'));
        }
    }

    /**
     * 用户组开启/禁用
     */
    public function admin_group_state() 
    {
        $id = input('x');
        $status = Db::name('auth_group')->where('id', $id)->value('status'); //判断当前状态情况
        if ($status == 1) {
            $statedata = array('status' => 0);
            Db::name('auth_group')->where('id', $id)->setField($statedata);
            $this->success('状态禁止');
        } else {
            $statedata = array('status' => 1);
            Db::name('auth_group')->where('id', $id)->setField($statedata);
            $this->success('状态开启');
        }
    }

    /**
     * 权限配置
     */
    public function admin_group_access() 
    {
        $admin_group = Db::name('auth_group')->where(array('id' => input('id')))->find();
        $data = AuthRule::get_ruels_tree();
        $this->assign('admin_group', $admin_group);
        $this->assign('datab', $data);
        return $this->fetch();
    }

    /**
     * 权限配置保存
     */
    public function admin_group_runaccess() 
    {
        $new_rules = input('new_rules/a');
        $imp_rules = implode(',', $new_rules);
        $sldata = array(
            'id' => input('id'),
            'rules' => $imp_rules,
        );
        if (Db::name('auth_group')->update($sldata) !== false) {
            Cache::clear();
            $this->success('权限配置成功', url('admin/Admin/admin_group_list'));
        } else {
            $this->error('权限配置失败', url('admin/Admin/admin_group_list'));
        }
    }

    /**
     * 重置密码
     */
    public function password_reset() 
    {
        $id = intval(input('id'));
        if (isset($id) && empty($id)) {
            $this->error('用户ID不存在', url('admin/Admin/admin_list'));
        }
        $update_arr = array(
            'password' => md5('admin123')
        );
        $update_result = Db::name('user')->where('id', $id)->setField($update_arr);
        if (1 == $update_result || 0 == $update_result) {
            //日志
            // $UserOperateModel = new UserOperateModel();
            // $UserOperateModel->addLog($id , '3');
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 用户修改密码
     */
    public function password_edit()
    {
        return $this->fetch();
    }

    /**
     * 处理用户修改密码
     */
    public function do_password_edit()
    {
        $userinfo = Session::get('userinfo');
        $data['id'] = $userinfo['id'];
        $data['password'] = md5(input('old'));
        $data['new'] = input('new');
        $data['re_new'] = input('re_new');
        //数据校验
        $result = $this->validate($data, 'Password');

        if (true !== $result) {
            $this->error($result);
        }
        $info = Db::name('user')->where('id',$data['id'])->update(['password' => md5($data['new'])]);
        
        if($info){
            $this->success('修改成功','admin/Login/logout');
        }else{
            $this->error('修改失败,请重试');
        }
    }


}
